package in.muton.edushare.registration;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.auth.EduShareAuthenticatedPage;
import in.muton.edushare.url.URLLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.validation.validator.PatternValidator;
import org.apache.wicket.validation.validator.StringValidator;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.constants.URLConstants;
import com.edushare.common.dao.TempUserDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.Enrolments;
import com.edushare.common.vo.UserDeptLink;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

public class InvitedUserLoginCreationPage extends EduShareAuthenticatedPage {

	private static final Log log = LogFactory.getLog(InvitedUserLoginCreationPage.class);
	private String newUserName;
	private String password;
	private String availability;
	
	public InvitedUserLoginCreationPage() {
		
		final Form<Void> form = new Form<Void>("form"){
			
			private static final long serialVersionUID = 7681296173199811990L;

			@Override
			protected void onSubmit() {
				
				if(StringUtil.isValid(newUserName)
						&& isUserNameAvailable(newUserName)){
					
					if(!StringUtil.IsMinNoOfAlphanumerics(newUserName, 2)){
						warn("At least two alphanumerics are required in user name");
						return;
					}
					
					Users u = EduShareSession.get().getLoggedInUser();
					u.setUserName(newUserName);
					u.setPassword(password);
					u.setStatus(Users.ACTIVE);
					
					//make all university links active
					for(UserRoles ur: u.getRoleList()){
						if(ur.getStatus() == UserRoles.STATUS_INVITED){
							ur.setStatus(UserRoles.STATUS_ACTIVE);
						}
					}
					
					for(UserDeptLink udl: u.getDepartmentLinks()){
						if(udl.getStatus() == UserDeptLink.STATUS_INVITED){
							udl.setStatus(UserDeptLink.STATUS_ACTIVE);
						}
					}
					
					for(Enrolments e: u.getEnrolments()){
						if(e.getStatus() == Enrolments.INVITED){
							e.setStatus(Enrolments.ENROLLED);
						}
					}
					
					u.setConfKey("");
					u.setLandingPageId(Users.LANDING_PAGE_USER_HOME);
					getSessionORMInterface().commitAllChanges();
					
					log.debug("Adding a new INVITED user: "+newUserName+"["+u.getUserId()+"]");
					setResponsePage(URLLoader.getPageClass(URLConstants.USER_PROFILE_PATH));
				
				}else{
					warn("User name already exists.");
				}
				super.onSubmit();
			}
		};
		add(form);
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupPlaceholderTag(true);
		form.add(feedback);
		
		PropertyModel<String> umodel = new PropertyModel<String>(this, "newUserName");
		final TextField<String> uname = new TextField<String>
										("uname", umodel);
		uname.add(StringValidator.minimumLength(ApplicationConstants.MIN_USERNAME_LENGTH));
		uname.add(new PatternValidator(ApplicationConstants.UNIQUE_NAME_PATTERN));
		uname.setRequired(true);
		form.add(uname);
		
		final Label unameWarn = new Label("availability", new PropertyModel<String>(this, "availability"));
		unameWarn.setOutputMarkupPlaceholderTag(true);
		unameWarn.setVisible(false);
		form.add(unameWarn);
		
		uname.add(new AjaxFormComponentUpdatingBehavior("onBlur"){

			private static final long serialVersionUID = 1466548945438993259L;

			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				if(isUserNameAvailable(uname.getInput())){
					InvitedUserLoginCreationPage.this.availability = "Available";
				}else{
					InvitedUserLoginCreationPage.this.availability = "Not Available";
				}
				unameWarn.setVisible(true);
				target.addComponent(unameWarn);
				target.addComponent(feedback);
			}
		});
		
		final PasswordTextField pass1 = new PasswordTextField
										("pass1", 
										  new PropertyModel<String>(this,"password"));
		pass1.add(StringValidator.minimumLength(ApplicationConstants.MIN_PASSWORD_LENGTH));
		pass1.setRequired(true);
		form.add(pass1);
		
		final PasswordTextField pass2 = new PasswordTextField
										("pass2", 
										  pass1.getModel());
		pass2.add(StringValidator.minimumLength(ApplicationConstants.MIN_PASSWORD_LENGTH));
		pass2.setRequired(true);
		form.add(pass2);
		
		form.add(new EqualPasswordInputValidator(pass1, pass2));
	}

	private boolean isUserNameAvailable(String input) {
		return new TempUserDAO(getSessionORMInterface()).isUserNameAvailable(input);
	}
}
